package net.yters.model.metric;

import java.util.ArrayList;

import net.yters.model.agents.DeciderAgent;
import net.yters.util.Box;
import cern.colt.matrix.DoubleFactory2D;
import cern.colt.matrix.DoubleMatrix2D;

public class HistoryCollector extends Metric {
	private static final long serialVersionUID = 1798857364809453614L;

	public Box f_headers = new Box(null);
	public Box f_history = new Box(null);
	private Integer f_columns = 0;

	public ArrayList<DeciderAgent> f_agents = new ArrayList<DeciderAgent>();

	public Box f_time = null;

	@SuppressWarnings("unchecked")
	public HistoryCollector(ArrayList<DeciderAgent> agents, Box time) {
		f_agents = agents;
		f_time = time;

		f_headers.f_value = new ArrayList<String>();
		for(DeciderAgent agent : f_agents) {
			for(String header : agent.f_state.keySet()) {
				((ArrayList<String>) f_headers.f_value).add(header);
			}
		}

		f_columns = ((ArrayList<String>) f_headers.f_value).size();
		f_history.f_value = DoubleFactory2D.dense.make(1, f_columns);
	}

	@Override
	public void execute() {
		ArrayList<Box> values = new ArrayList<Box>();
		for(DeciderAgent agent : f_agents) {
			values.addAll(agent.f_state.values());
		}

		double[] moment = new double[f_columns];
		for(int i = 0; i < f_columns; i++) {
			moment[i] = (Double) values.get(i).f_value;
		}

		DoubleMatrix2D momentVector = DoubleFactory2D.dense.make(moment,1); 
		
		f_history.f_value = DoubleFactory2D.dense.appendRows(
				(DoubleMatrix2D) f_history.f_value, 
				momentVector);
	}
	
	@SuppressWarnings("unchecked")
	public String historyToString() {
		String result = new String();
		
		// Format:
		// <history1 value1 name> ... <history1 valuem name>  <history2 value1 name> ... <history2 valuem name>  <historyn value1 name> ... <historyn valuem name>
		// <history1 value1> ... <history1 valuem>  <history2 value1> ... <history2 valuem>  <historyn value1> ... <historyn valuem>
		for(String header : (ArrayList<String>) f_headers.f_value) {
			result = result.concat(header + " ");
		} 
		result = result.concat("\n");
		
		String[] temp = ((DoubleMatrix2D) f_history.f_value).toString().split("\n");
		for(int i = 2; i < temp.length; i++) result = result.concat(temp[i].concat("\n"));
		
		return result;
	}
}
